package cn.edu.hust.sse.software7.class3.servlet.common;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hust.sse.software7.class3.entities.EBProduct;
import cn.edu.hust.sse.software7.class3.serviceImpl.EBProductServiceImpl;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class ImageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Long id = null;
		id = Long.parseLong(req.getParameter("id"));
		if (id == null) {
			return;
		}
		EBProduct ebp = new EBProductServiceImpl().getProdById(id);

		if (ebp == null) {
			return;
		}
		Blob b = ebp.getProductImage();
		String type = req.getParameter("type");

		ImagesService is = ImagesServiceFactory.getImagesService();
		Image image = ImagesServiceFactory.makeImage(b.getBytes());
		Transform tf = ImagesServiceFactory.makeResize(120, 90);
		if (type.equals("2")) {
			tf = ImagesServiceFactory.makeResize(200, 150);
		}
		if (type.equals("3")) {
			tf = ImagesServiceFactory.makeResize(300, 225);
		}
		
		if (type.equals("1")) {
		}
		
		Image newImage = is.applyTransform(tf, image);
		byte[] imageData = newImage.getImageData();
		Blob blob = new Blob(imageData);

		resp.setContentType("image/jpeg;charset=utf-8");
		resp.getOutputStream().write(blob.getBytes());
		resp.getOutputStream().close();
	}

}
